package com.youchuang.common;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionInvocation;
import com.youchuang.entry.BaseResponse;
import com.youchuang.factory.EntryFactory;
import org.apache.log4j.Logger;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * struts2返回类型（String类型）
 * Created by Winchell on 2016/10/28 0028.
 */
public class StringResult extends StrutsResultSupport {
    private static final long serialVersionUID = 1L;
    private static Logger logger = Logger.getLogger(StringResult.class.getSimpleName());

    private String contentTypeName;
    private String stringName = "";

    public StringResult() {
        super();
    }

    public StringResult(String location) {
        super(location);
    }

    protected void doExecute(String finalLocation, ActionInvocation invocation)
            throws Exception {
        HttpServletResponse response = (HttpServletResponse) invocation
                .getInvocationContext().get(HTTP_RESPONSE);

        String contentType = conditionalParse(contentTypeName, invocation);
        if (contentType == null) {
            contentType = "text/plain; charset=UTF-8";
        }
        response.setContentType(contentType);
        PrintWriter out = response.getWriter();
        String result = (String) invocation.getStack().findValue(stringName);
        if (StringUtils.isEmpty(result)) {
            BaseResponse baseResponse = EntryFactory.getBaseResponse();
            baseResponse.setSuccess(true);
            baseResponse.setMsg(Constant.NOT_DATA_MES);
            result = JSONObject.toJSONString(baseResponse);
            logger.info("response json = " + result);
        }
        out.println(result);
        out.flush();
        out.close();
    }

    public String getContentTypeName() {
        return contentTypeName;
    }

    public void setContentTypeName(String contentTypeName) {
        this.contentTypeName = contentTypeName;
    }

    public String getStringName() {
        return stringName;
    }

    public void setStringName(String stringName) {
        this.stringName = stringName;
    }
}
